import Food from "./food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";

class GameControl {
  snake: Snake;
  food: Food;
  scrorePanel: ScorePanel;
  direction: string = "ArrowRight";
  isLive = true;
  constructor() {
    this.food = new Food();
    this.snake = new Snake();
    this.scrorePanel = new ScorePanel();

    this.init();
  }
  init() {
    document.addEventListener("keydown", this.keydownHandler.bind(this));
    this.run();
  }
  keydownHandler(event: KeyboardEvent) {
    this.direction = event.key;
    console.log(this.direction);
  }
  run() {
    // 根据方向 蛇的位置改变
    let X = this.snake.X;
    let Y = this.snake.Y;
    switch (this.direction) {
      case "ArrowLeft":
        X -= 10;
        break;
      case "ArrowUp":
        Y -= 10;
        break;
      case "ArrowRight":
        X += 10;
        break;
      case "ArrowDown":
        Y += 10;
        break;
    }
    this.checkEat(X, Y);
    try {
      this.snake.X = X;
      this.snake.Y = Y;
    } catch (e) {
      alert(e.message + "Game Over");
      this.isLive = false;
    }

    this.isLive &&
      setTimeout(() => {
        this.run();
      }, 300 - (this.scrorePanel.level - 1) * 30);
  }

  checkEat(X: number, Y: number) {
    if (X === this.food.X && Y === this.food.Y) {
      this.food.change();
      this.scrorePanel.addScore();
      this.snake.addBdy();
    }
  }
}

export default GameControl;
